package com.schoolCommunity.util;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * author: YTH
 * 2020/6/13
 * 上传下载工具类
 */
@Component
public class UploadCommodityPicture {

    Logger log = Logger.getLogger(UploadCommodityPicture.class);

    //传入文件以及地点名字
    public String upload(MultipartFile file, String placeName) {
        try {

            //原始名字
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
            String createTime = df.format(new Date());// new Date()为获取当前系统时间

            //现在的时间是
            log.info("上传图片的时间是" + createTime);

//        System.setProperty("sun.jnu.encoding","utf-8");

            //上传图片的位置
            String filePath = "E:/项目/学校社区/schoolCommunityVue/src/schoolCommunityPicture/commodityPicture/";
            //上传图片的名字
            String reallyName = placeName + "_" + createTime + ".jpg";
            fileName = filePath + reallyName;
            log.info("得到的图片绝对路径是" + fileName);
            //使用唯一识别名建立输入
            File destinationfile = new File(fileName);
            // 判断路径是否存在
            if (!destinationfile.getParentFile().exists()) {
                destinationfile.getParentFile().mkdirs();
            }
            //写入
            file.transferTo(destinationfile);
            //写入文件之后复制资源
            copyFileUsingFileChannels(destinationfile,reallyName);
            //返回名字
            return reallyName;
        } catch (Exception e) {
            return "上传失败";
        }

    }

    private static void copyFileUsingFileChannels(File source, String reallyName) throws IOException {

        System.out.println("进入了复制的方法");

        final  String BackPath = "E:/项目/学校社区/vue-admin-template/src/views/schoolCommunityPicture/commodityPicture/";

        String BackName = BackPath+reallyName;

        //新建文件
        File dest = new File(BackName);

        // 判断路径是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        FileChannel inputChannel = null;

        FileChannel outputChannel = null;

        try {

            inputChannel = new FileInputStream(source).getChannel();

            outputChannel = new FileOutputStream(dest).getChannel();

            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());

        } finally {

            inputChannel.close();

            outputChannel.close();

        }

    }

}
